import { showMessage } from '@/components/antd-comp/message'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { useDictStore } from '@/store/dictStore'
import { useBuriedEvent } from '@/util/buried'
import { Button, Form, Input, Radio, Select, Space } from 'antd'
import { ArrowLeft } from 'lucide-react'
import { useEffect, useRef, useState, useContext } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import ShadTooltip from '../../components/ShadTooltipComponent'
import IconUpload from '../../components/antd-comp/icon-upload'
import { getEmbeddingModel } from '../../controllers/API'
import { createFileLib } from '../../controllers/API/index'
import { updateKnowledgeLib } from '../../controllers/API/knowledge'
import { MODELS_OBJ } from './constants'
import './css/create.less'
import { userContext } from '../../contexts/userContext'

const { TextArea } = Input

export default function CreatePage() {
  const [loading, setLoading] = useState(false)
  const { t } = useTranslation()
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const { fileLibBuriedEvent } = useBuriedEvent()
  const { user, setUser } = useContext(userContext)

  const initValues = {
    name: '',
    model: '',
    catetory: undefined,
    tag: '',
    description: ''
  }

  // 跳转带入参数
  const { state } = useLocation()
  const isEdit = state.type === 'edit'

  // 类型选择
  const [typeList, setTypeList] = useState([])
  const { loadDictOptions } = useDictStore()
  // const loadTypeList = (type = 'category') => {
  //   loadDictOptions(type).then(res => {
  //     setTypeList(res)
  //   })
  // }
  const loadTypeList = () => {
    if(user.role.includes('enterprise_admin')){
      setTypeList([{id: -1, label: '企业知识库'}, {id: 1, label: '个人知识库'}])
    }else{
      setTypeList([{id: 1, label: '个人知识库'}])
    }
  }
  const [icon, setIcon] = useState(undefined)

  useEffect(() => {
    console.log('isEdit && state.data', isEdit, state.data)
    if (isEdit && state.data) {
      Object.keys(initValues).forEach(key => {
        initValues[key] = state.data[key] ? state.data[key] : initValues[key]
      })
      if (state.data.icon && state.data.icon !== 'None') {
        setIcon(state.data.icon)
      }

      form.setFieldsValue(initValues)
    }
    loadTypeList()
    // loadIconList()
  }, [])

  const [modelOptions, setModelOptions] = useState([])
  useEffect(() => {
    getEmbeddingModel().then(res => {
      const models = res.models || []
      setModelOptions(models)
      form.setFieldsValue({ model: models[0] || '' })
    })
  }, [])

  const submit = e => {
    e.preventDefault()
    form
      .validateFields()
      .then(values => {
        setLoading(true)
        if (icon) {
          values.icon = icon
        } else if (defaultIcon.current) {
          values.icon = defaultIcon.current
        }
        isEdit ? updateSubmit(values) : createSubmit(values)
      })
      .catch(err => {
        console.log('err', err)
      })
  }
  const createSubmit = values => {
    createFileLib(values)
      .then((res: any) => {
        fileLibBuriedEvent({
          page: '创建知识库页面',
          event_name: '【完成创建】按钮',
          data_id: res.id,
          detail: JSON.stringify({ 类型: values.catetory, 模型: values.model, 结果: '成功' })
        })
        showMessage({
          content: '创建成功',
          type: 'success'
        })
        navigate('/filelib')
      })
      .finally(() => {
        setLoading(false)
      })
      .catch(err => {
        console.log(err)
        fileLibBuriedEvent({
          page: '创建知识库页面',
          event_name: '【完成创建】按钮',
          detail: JSON.stringify({ 类型: values.catetory, 模型: values.model, 结果: '失败' })
        })
      })
  }

  const updateSubmit = values => {
    values.knowledge_id = state.data.id
    updateKnowledgeLib(values)
      .then(res => {
        fileLibBuriedEvent({
          page: '编辑知识库页面',
          event_name: '【完成编辑】按钮',
          data_id: values.knowledge_id,
          detail: JSON.stringify({ 类型: values.catetory, 结果: '成功' })
        })
        showMessage({
          content: '编辑成功',
          type: 'success'
        })
        navigate('/filelib')
      })
      .finally(() => {
        setLoading(false)
      })
      .catch(err => {
        console.log(err)
        fileLibBuriedEvent({
          page: '编辑知识库页面',
          event_name: '【完成编辑】按钮',
          data_id: values.knowledge_id,
          detail: JSON.stringify({ 类型: values.catetory, 结果: '失败' })
        })
      })
  }

  const cancel = () => {
    if (isEdit) {
      fileLibBuriedEvent({
        page: '编辑知识库页面',
        event_name: '【取消】按钮',
        data_id: state.data.id
      })
    } else {
      fileLibBuriedEvent({
        page: '创建知识库页面',
        event_name: '【取消】按钮'
      })
    }
    navigate('/filelib')
  }

  /**
   * ICON上传组件相关
   */
  const [iconFileList] = useState([])
  const handleSelectPic = pic => {
    setIcon(pic)
  }
  const defaultIcon = useRef('')
  const setDefaultIcon = val => {
    defaultIcon.current = val
  }

  return (
    <div className="relative h-full w-full px-[32px] py-[32px]">
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <div className=" h-full overflow-y-auto rounded-[6px] bg-[#ffffff]">
        <div className="flex items-center justify-between px-[32px] pb-[24px] pt-[32px]">
          <div className="flex items-center">
            <ShadTooltip content="back" side="top">
              <button
                className="extra-side-bar-buttons w-[36px]"
                onClick={() => {
                  navigate('/filelib')
                }}
              >
                <Link
                  to="/filelib"
                  onClick={() => {
                    if (isEdit) {
                      fileLibBuriedEvent({
                        page: '编辑知识库页面',
                        event_name: '【返回】按钮',
                        data_id: state.data.id
                      })
                    } else {
                      fileLibBuriedEvent({
                        page: '创建知识库页面',
                        event_name: '【返回】按钮'
                      })
                    }
                  }}
                >
                  <ArrowLeft className="side-bar-button-size" />
                </Link>
              </button>
            </ShadTooltip>
            <span className=" pl-4 text-sm font-black text-gray-700">
              {isEdit ? t('lib.editLibrary') : t('lib.createLibrary')}
            </span>
          </div>
        </div>
        <div className="k-create-content">
          <Form form={form} layout="vertical" initialValues={initValues}>
            <Form.Item
              name="name"
              label={t('lib.libraryName')}
              required
              rules={[
                { required: true, message: t('lib.nullLimit') },
                { max: 50, message: t('lib.limit50Len') }
              ]}
              className="formCont_mar"
            >
              <Input
                name="k-create-name"
                autoComplete="off"
                placeholder={t('lib.createLibName')}
                style={{ width: '400px' }}
              />
            </Form.Item>
            <Form.Item
              className="formCont_mar"
              name="model"
              label={t('lib.model')}
              required
              rules={[{ required: true, message: t('lib.nullLimit') }]}
            >
              <Select allowClear placeholder={t('lib.selectModel')} disabled={isEdit} style={{ width: '400px' }}>
                {modelOptions.map(model => (
                  <Select.Option key={model} value={model}>
                    {MODELS_OBJ[model] || model}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              className="formCont_mar"
              name="catetory"
              label={t('lib.type')}
              required
              rules={[{ required: true, message: t('lib.nullLimit') }]}
            >
              <Radio.Group>
                {typeList.map(({ id, label }) => (
                  <Radio key={id} value={id}>
                    {label}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>

            {/* <Form.Item
              className="formCont_mar"
              name="tag"
              label={t('lib.tag')}
              rules={[{ max: 100, message: t('lib.limit100Len') }]}
            >
              <Input style={{ width: '400px' }} disabled={isEdit} placeholder={t('lib.inputTag')} autoComplete="off" />
            </Form.Item> */}

            <Form.Item
              className="formCont_mar"
              name="description"
              label={t('lib.description')}
              rules={[
                { required: true, message: t('lib.descMess') },
                { max: 200, message: t('lib.descriptionLimit') }
              ]}
            >
              <TextArea placeholder={t('lib.descMess')} autoSize={{ minRows: 3 }} style={{ width: '600px' }} />
            </Form.Item>
            <Form.Item style={{ width: '600px' }} className="formCont_mar">
              <IconUpload
                defaultFileList={iconFileList}
                logo={icon}
                form={form}
                validateNames={['name', 'description']}
                onSelect={pic => handleSelectPic(pic)}
                setDefault={setDefaultIcon}
              ></IconUpload>
            </Form.Item>
            {/* 适配 media >2000 display:none */}
            <Form.Item>
              <Space>
                <ThemeBtn className="closeBtnWid btnPost_fileLib_hid" htmlType="submit" onClick={e => submit(e)}>
                  {isEdit ? t('lib.editDone') : t('lib.createDone')}
                </ThemeBtn>
                <Button
                  className="closeBtnStyles closeBtnWid btnPost_fileLib_hid"
                  shape="round"
                  onClick={() => cancel()}
                >
                  {t('cancel')}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>
      {/* 适配 display:none 2000 < media > 2000 显示 */}
      <Space className="btnPost_fileLib">
        <ThemeBtn className="closeBtnWid h-[34px] w-[92px]" htmlType="submit" onClick={e => submit(e)}>
          {isEdit ? t('lib.editDone') : t('lib.createDone')}
        </ThemeBtn>
        <Button className="closeBtnStyles closeBtnWid h-[34px] w-[92px]" shape="round" onClick={() => cancel()}>
          {t('cancel')}
        </Button>
      </Space>
    </div>
  )
}
